package com.example.lbs.service;

import com.example.lbs.model.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Service
public class ShopCacheService {
    private final StringRedisTemplate redis;

    // 缓存过期时间（可调整）
    private static final long TTL_SECONDS = 12 * 60 * 60;

    public ShopCacheService(StringRedisTemplate redis) {
        this.redis = redis;
    }

    public void cacheShopDetail(Shop shop) {
        String key = "shop:detail:" + shop.getId();
        Map<String, String> map = Map.of(
                "id", shop.getId().toString(),
                "name", shop.getName(),
                "brand", shop.getBrand(),
                "address", shop.getAddress(),
                "lng", String.valueOf(shop.getLng()),
                "lat", String.valueOf(shop.getLat())
        );
        redis.opsForHash().putAll(key, map);
        redis.expire(key, java.time.Duration.ofSeconds(TTL_SECONDS));
    }

    public void delete(Long id) {
        redis.delete("shop:detail:" + id);
    }

    public Optional<Shop> getShopDetail(Long id) {
        String key = "shop:detail:" + id;
        Map<Object, Object> m = redis.opsForHash().entries(key);
        if (m == null || m.isEmpty()) return Optional.empty();
        Shop s = new Shop();
        s.setId(Long.valueOf((String) m.get("id")));
        s.setName((String) m.get("name"));
        s.setBrand((String) m.get("brand"));
        s.setAddress((String) m.get("address"));
        s.setLng(Double.parseDouble((String) m.get("lng")));
        s.setLat(Double.parseDouble((String) m.get("lat")));
        return Optional.of(s);
    }
}